<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { isString } from '@/utils/is'
import { ElTag,ElMessage } from 'element-plus'
import { Table } from './Table'
import { getListApi, delListApi } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { reactive, ref, unref,computed } from 'vue'
import { useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useTagsViewStoreWithOut } from '@/store/modules/tagsView'
import {TableColumn} from "@/components/DTable/src/Table/src/types";
const tagViewStore = useTagsViewStoreWithOut()

const { currentRoute } = useRouter()
const tagsViewStore = useTagsViewStore()
const setSelectTag = tagsViewStore.setSelectedTag
defineOptions({
  name: 'DTable'
})

const props = defineProps({
  table: {
    type: Object,
    default: () => {}
  }
})
const { push } = useRouter()

const ids = ref<string[]>([])
const searchParams = ref({})
const postParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const headerFilterSumit = (data: any) => {
  postParams.value['filter'][data.field] = data
  getList()
  // console.log('++++++++++++++++++++++++++++++++')
  // console.log(data)
}

const handleSortChange = (prop, order) =>{
  // console.log(`Sorting by ${prop} ${order}`);
  postParams.value['order'] = {"field": prop, "order": order}
  getList()
}
const listUrl = (props.table.url && isString(props.table.url)) ? props.table.url : props.table.url.list
// const delUrl = props.table.delurl||props.table.url.del

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi(listUrl, {
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    },
            {
              ...unref(postParams),
            })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async (delUrl) => {
    const res = await delListApi(delUrl, unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList,refresh } = tableMethods

getList()

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const { t } = useI18n()

const btns = {
  add:{
    btntype: 'primary',
    name: '添加'
  },
  del: {
    btntype: 'danger',
    name: '删除'
  },
  refresh:{
    btntype: 'primary',
    name: '刷新'
  },
}

const defaultBtns = {
  refresh:{
    btntype: 'primary',
    name: '刷新'
  },
}

const crudSchemas = reactive<CrudSchema[]>(props.table.columns)
const btnList = reactive([])
const buttons = () => {
  if(!props.table.buttons) return []
  if(btnList.length > 0) return btnList;
  Object.keys(props.table.buttons).forEach( k =>{
    const item = {
      type: k,
      name: btns[k]['name'],
      btntype: btns[k]['btntype'],
      url: props.table.buttons[k]
    }
    btnList.push(item)
  })

  Object.keys(defaultBtns).forEach( k =>{
    const item = {
      type: k,
      name: btns[k]['name'],
      btntype: btns[k]['btntype'],
      url: props.table.buttons[k]
    }
    btnList.push(item)
  })
  return btnList
}
// console.log(buttons())
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const AddAction = () => { push('/example/example-add') }

const delLoading = ref(false)

const multipleSelection = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  return unref(ids)
}

const delData = async (delurl: String, row: TableData | null) => {
  // const elTableExpose = await getElTableExpose()
  // ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  multipleSelection(row)
  delLoading.value = true
  await delList(delurl, unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const addTags = () => {
  const { name } = unref(currentRoute)
  if (name) {
    setSelectTag(unref(currentRoute))
    tagsViewStore.addView(unref(currentRoute))
  }
}
const action = (row: TableData, type: string) => {
  push(`/example/example-${type}?id=${row.id}`)
  tagViewStore.add(`/example/example-${type}`, {id:`${row.id}`})
}

const btnAction = (btn: any) =>{
  if(btn.type == 'refresh'){
    refresh()
    return;
  }
  if(!btn.url) return
  let url = []
  if(btn.url.indexOf(':/') == -1) {
    url[1] = btn.url
  }else{
    url = btn.url.split(':/')
  }
  if(btn.type == 'del'){
    delData(btn.url, null)
    return;
  }



  switch (url[0]) {
    case 'push' : push(url[1]); break;
    default: push(url[1])
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
        <BaseButton  v-for="(it,index) in buttons()" :key="index" :type="it.btntype || 'primary'" size="small" @click="btnAction(it)">{{ it.name }}</BaseButton>
    </div>

<!--    :customContent=false-->
<!--    :showAction=true-->

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      v-model:multipleSelection="multipleSelection"
      :columns="allSchemas.tableColumns"
      :summaryname="props.table.summary"
      :data="dataList"
      :loading="loading"
      :showAction=true
      :pagination="{
        total: total
      }"
      @header-filter-sumit="headerFilterSumit"
      @register="tableRegister"
      @sort-change="handleSortChange"
    />
  </ContentWrap>
</template>
@/hooks/event/useEventBus
